package com.xl.core.util.orc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

/**
 * Tesseract OCR识别图片信息
 * 
 * @author Administrator
 * 
 */
public class ORCHelper {

	private final static Logger log = Logger.getLogger(ORCHelper.class);

	private static final String LANG_OPTION = "-l"; // 英文字母小写l，并非数字1
	private static final String OS = System.getProperty("os.name")
			.toLowerCase(); // 操作系统
	private static String tessPath = "D://Application//Tesseract-OCR";

	/**
	 * 识别身份证图片
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static String recognizeIdCard(String filePath) throws Exception {

		// 判断文件是否存在
		File imageFile = new File(filePath);
		if (!imageFile.exists()) {
			return null;
		}

		// 图片预处理，生成临时文件
		File tempImage = ImageFilter.cleanIdCardImage(imageFile);

		// 获取识别到的信息
		List<String> info = listImgValue(tempImage);
		if (info == null || info.size() == 0) {
			return null;
		}

		// 通过正则表达式，提取到身份证号码
		Pattern pattern = Pattern.compile("\\d{18}|\\d{15}");
		for (int i = info.size() - 1; i >= 0; i--) {
			Matcher matcher = pattern.matcher(info.get(i));
			if (matcher.find()) {
				return matcher.group();
			}
		}
		return null;
	}

	/**
	 * 识别银行卡图片
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static String recognizeBankCard(String filePath) throws Exception {

		// 判断文件是否存在
		File imageFile = new File(filePath);
		if (!imageFile.exists()) {
			return null;
		}

		// 图片预处理，生成临时文件
		File tempImage = ImageFilter.cleanBankCardImage(imageFile);

		// 获取识别到的信息
		List<String> info = listImgValue(tempImage);
		if (info == null || info.size() == 0) {
			return null;
		}

		// 通过正则表达式，提取到银行卡号
		Pattern pattern = Pattern
				.compile("\\d{19}|\\d{18}|\\d{17}|\\d{16}|\\d{15}");
		for (int i = info.size() - 1; i >= 0; i--) {

			String str = info.get(i).trim().replaceAll("\\s*", "");
			Matcher matcher = pattern.matcher(str);
			if (matcher.find()) {
				return matcher.group();
			}
		}
		return null;
	}

	/**
	 * 识别图片信息(原始图片，不做处理)
	 * 
	 * @param imageFile
	 * @param imageFormat
	 * @return
	 * @throws Exception
	 */
	public static List<String> listImgValue(File imageFile) throws Exception {

		// 临时输出文件目录
		File outputFile = new File(imageFile.getParentFile(), "output");
		// 返回的扫描值
		List<String> value = new ArrayList<String>();
		// 命令
		List<String> cmd = new ArrayList<String>();
		if (OS.indexOf("windows") >= 0) {
			cmd.add(tessPath + "//tesseract");
		} else if (OS.indexOf("linux") >= 0) {
			cmd.add("tesseract");
		} else {
			cmd.add(tessPath + "//tesseract");
		}
		cmd.add(imageFile.getName());
		cmd.add(outputFile.getAbsolutePath());
		cmd.add(LANG_OPTION);
		cmd.add("chi_sim");

		ProcessBuilder pb = new ProcessBuilder();
		pb.directory(imageFile.getParentFile());
		pb.command(cmd);
		pb.redirectErrorStream(true);

		Process process = pb.start();
		// tesseract.exe 1.jpg 1 -l chi_sim
		int w = process.waitFor();

		// 删除临时文件
		imageFile.delete();

		if (w == 0) {
			File outTempFile = new File(outputFile.getAbsolutePath() + ".txt");
			BufferedReader in = new BufferedReader(new InputStreamReader(
					new FileInputStream(outTempFile), "UTF-8"));

			String str;
			while ((str = in.readLine()) != null) {
				value.add(str);
			}
			in.close();

			outTempFile.delete();

		} else {
			String msg;
			switch (w) {
			case 1:
				msg = "Errors accessing files.There may be spaces in your image's filename.";
				break;
			case 29:
				msg = "Cannot recongnize the image or its selected region.";
				break;
			case 31:
				msg = "Unsupported image format.";
				break;
			default:
				msg = "Errors occurred.";
			}

			log.debug(msg);
		}
		return value;
	}

	public static void main(String[] args) {

		try {

			// List<String> list = ORCHelper.listImgValue(new File(
			// "E:\\图片\\003.jpg"));
			//
			// for (String str : list) {
			// System.out.println(str);
			// }
			System.out.println(recognizeBankCard("E:\\图片\\101.jpg"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}